<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/5/29
  Time: 9:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <title>Title</title>
    <script src="../../js/jquery-3.3.1.min.js" charset="utf-8"></script>
    <script src="../../js/cookie/jquery.cookie.js" charset="utf-8"></script>
    <script src="../../layui-v2.4.5/layui/layui.js" charset="utf-8"></script>
    <script src="/js/layui/form_verify.js"></script>
    <link rel="stylesheet" href="../../layui-v2.4.5/layui/css/layui.css" media="all">
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>上传商品轮播图</legend>
</fieldset>

<div class="layui-upload">
    <input id="commodityId" value="${commodityId}" type="hidden">
    <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
    <button type="button" class="layui-btn" id="testListAction2" >保存</button>
    <div class="layui-upload-list">
        <table class="layui-table">
            <thead>
            <tr><%--<th>文件名</th>
            <th>大小</th>--%>
                <%--   <th>状态</th>--%>
                <th>预览</th>
                <th>显示顺序</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="demoList">
            <c:forEach items="${listSlid}" var="sild" varStatus="ind">
                <tr id="upload-${ind.index}">
                <td> <input type="hidden" name="images"  value="${sild.path}">
                <input type="hidden" name="imgPathId"  value="${sild.id}">
                <img src="${sild.path}" style="width: 100px;height: 100px; " >
                </td>
                <td><input type="text" placeholder="填写图片顺序" name="picIndex" value="${sild.number}" style="width: 130px" /></td>
                <td>
                    <button class="layui-btn layui-btn-mini layui-btn-danger demo-delete delTr">删除</button>
                </tr>

            </c:forEach>
            <%--<c:if test="${!empty listSlid}" >--%>
                <%--<c:forEach varStatus="ind" items="${listSlid}" var="list">--%>
                    <%--<tr id="upload-${ind.index}">--%>
                        <%--<td> <input type="hidden" name="images"  value="${list.path}">--%>
                            <%--<input type="hidden" name="imgPathId"  value="${list.id}">--%>
                            <%--<img src="${list.path}" style="width: 100px;height: 100px; " >--%>
                        <%--</td>--%>
                        <%--<td><input type="text" placeholder="填写图片顺序" name="picIndex" value="${list.number}" style="width: 130px" /></td>--%>
                        <%--<td><button class="layui-btn layui-btn-mini layui-btn-danger demo-delete delTr">删除</button></td>--%>
                    <%--</tr>--%>
                <%--</c:forEach>--%>
            <%--</c:if>--%>
            </tbody>
        </table>
    </div>
    <input type="hidden" id="tempPath">
    <input type="hidden" id="delIds">
    <button type="button" class="layui-btn" id="testListAction" style="display: none">保存</button>

</div>
</body>
<script>
    $(function () {
        $(".delTr").click(function () {
            var tr= $(this).parent().parent();
            var firstTD=$(tr).children('td').eq(0).find("input").eq(1).val();
            var ids= $("#delIds").val();
            if(ids!=null&&ids!=''){
                $("#delIds").val(ids+","+"'"+firstTD+"'");
            }else{
                $("#delIds").val("'"+firstTD+"'");
            }
            tr.remove();
        })
    })
    layui.use('upload', function(){
        var $ = layui.jquery
            ,upload = layui.upload,layer=layui.layer;

        $(document).on('click','#testListAction2',function(){
            var re=/^\\d+$/;
            var arr =[];
            $("input[name='images']").each(function () {
                var image = $(this).val();
                arr.push(image)
            })
            var pInd=[];
            $("input[name='picIndex']").each(function () {
                var picIndex = $(this).val();
                /*  if(!re.test(picIndex)||picIndex==null||picIndex==""){
                      layer.msg('请输入图片显示索引序号！', {
                          icon: 5,
                          time: 1000 //2秒关闭（如果不配置，默认是3秒）
                      }, function(){
                          //window.location.reload()
                      });
                      return false;
                  }else{

                  }*/
                pInd.push(picIndex)
            })
            var imgPathId=[];
            $("input[name='imgPathId']").each(function () {
                var id = $(this).val();
                imgPathId.push(id)
            })
            var ids= $("#delIds").val();
            //执行ajax保存数据
            $.ajax({
                url: '/shop/saveImages',
                type: 'POST', //GET
                async: false,    //或false,是否异步
                data: {commodityId:'${commodityId}'
                    ,imgPaths:arr,picInd:pInd,
                    imgPathId:imgPathId,delIds:ids
                },
                timeout: 50000,    //超时时间
                dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                success: function (data) {
                    if(data.code=='0'){
                        layer.msg('保存成功', {
                            icon: 6,
                            time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            window.location.reload()
                        });
                        /* setTimeout(function () {
                             window.location.reload()
                         },1000)*/
                    }else{
                        layer.msg('保存失败，请稍后重试！', {
                            icon: 5,
                            time: 1000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            //window.location.reload()
                        });
                    }

                },
            });

        });
        //多文件列表示例
        var demoListView = $('#demoList'),uploadListIns = upload.render({
            elem: '#testList'
            ,url: '/adminSystem/callBackImages'
            ,accept: 'file'
            ,multiple: true
            ,auto: false
            ,bindAction: '#testListAction'
            ,choose: function(obj){
                /*  $("#testListAction2").hide();
                    $("#testListAction2").attr("disabled","disabled");
                  $("#testListAction").show();*/
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
                    // convertImgToBase64(0, getObjectURL(file), function (base64Img) {
                    //获取年月日时分秒
                    var date = new Date();
                    var year = date.getFullYear();
                    var month = date.getMonth()+1;
                    var day = date.getDate();

                    $.ajax({
                        url: '/qiniu/uploadImages',
                        type: 'POST', //GET
                        async: false,    //或false,是否异步
                        data: {
                            images: result.split(",")[1],
                            key:"/lunbotu/"+year+'_'+month+'_'+day+'_'
                        },
                        timeout: 50000,    //超时时间
                        dataType: 'text',    //返回的数据格式：json/xml/html/script/jsonp/text
                        success: function (data) {
                            $("#tempPath").val(data)
                        },
                    });
                    //});
                    var img= $("#tempPath").val();

                    var tr = $(['<tr id="upload-'+ index +'">'
                        /*    ,'<td>'+ file.name +'</td>'*/
                        /*                    ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'*/
                        ,'<td>'
                        ,'<input type="text" style="display: none" name="images" value="'+img+'">'
                        ,'<img src="'+img+'" style="width: 100px;height: 100px; " >'
                        ,'</td>'
                        ,'<td>'
                        ,'<input type="text" placeholder="填写图片顺序" name="picIndex" style="width: 130px" />'
                        ,'<input type="hidden"  name="imgPathId" />'
                        ,'</td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });
                    demoListView.append(tr);
                });
            }
            ,done: function(res, index, upload){
                var arr =[];
                $("input[name='images']").each(function () {
                    var image = $(this).val();
                    arr.push(image)
                })
                var pInd=[];
                $("input[name='picIndex']").each(function () {
                    var picIndex = $(this).val();
                    pInd.push(picIndex)
                })
                var imgPathId=[];
                $("input[name='imgPathId']").each(function () {
                    var id = $(this).val();
                    imgPathId.push(id)
                });
                var ids= $("#delIds").val();
                //执行ajax保存数据
                $.ajax({
                    url: '/adminSystem/saveImages',
                    type: 'POST', //GET
                    async: false,    //或false,是否异步
                    data: {id:'${id}',width:750,height:500,
                        agentId:'${agentId}',imgPaths:arr,picInd:pInd,
                        imgPathId:imgPathId,delIds:ids
                    },
                    timeout: 50000,    //超时时间
                    dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    success: function (data) {
                        if(data.code=='0'){
                            layer.msg("保存成功!");
                            setTimeout(function () {
                                window.location.reload()
                            },1000)
                        }else{
                            layer.msg("保存失败，请稍后重试!");
                        }

                    },
                });
            }
            ,error: function(index, upload){
            }
        });
    });
</script>
</html>
